﻿namespace YunQue.WebApi.Common
{
    /// <summary>
    /// route属性缓存类
    /// </summary>
    public class RouteAttributeCache
    {
        private static ConcurrentDictionary<string, List<Attribute>> urlAttributeDic = new ConcurrentDictionary<string, List<Attribute>>();

        /// <summary>
        /// 初始化路由属性缓存
        /// </summary>
        /// <param name="routeAttribute"></param>
        public static void Initialize(Dictionary<string, List<Attribute>> routeAttribute)
        {
            if(routeAttribute != null && routeAttribute.Count > 0)
            {
                foreach (var item in routeAttribute)
                {
                    urlAttributeDic.AddOrUpdate(item.Key, item.Value, (key, oldValue) => item.Value);
                }
            }
        }
        /// <summary>
        /// 获取路由属性
        /// </summary>
        /// <param name="route"></param>
        /// <returns></returns>
        public static List<Attribute> GetRouteAttributes(string route)
        {
            if (string.IsNullOrEmpty(route)) return null;
            route = route.TrimStart('/').ToLower();
            if (urlAttributeDic.TryGetValue(route, out var attributes))
            {
                return attributes;
            }
            return null;
        }
        /// <summary>
        /// 获取路由的自定义Attribute
        /// </summary>
        /// <typeparam name="TAttribute"></typeparam>
        /// <param name="route"></param>
        /// <returns></returns>
        public static TAttribute GetAttribute<TAttribute>(string route) where TAttribute : Attribute
        {
            var attributes = GetRouteAttributes(route);
            if (attributes == null || attributes.Count == 0) return null;
            return attributes.Where(a => a is TAttribute).Select(a => a as TAttribute).FirstOrDefault();
        }
        /// <summary>
        /// 获取路由的APIPermissionAttribute
        /// </summary>
        /// <param name="route"></param>
        /// <returns></returns>
        public static APIPermissionAttribute GetAPIPermissionAttribute(string route)
        {
            return GetAttribute<APIPermissionAttribute>(route);
        }
        /// <summary>
        /// 获取路由的AllowAnonymousAttribute
        /// </summary>
        /// <param name="route"></param>
        /// <returns></returns>
        public static AllowAnonymousAttribute GetAllowAnonymousAttribute(string route)
        {
            return GetAttribute<AllowAnonymousAttribute>(route);
        }
    }
}
